package cn.huiyunche.base.service.framework.security;

import cn.huiyunche.base.service.vo.UserVo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * jwt工具.
 * <p>
 *
 * @author zhaoshb
 * @since 0.0.1
 */
public class JwtUtils {

    private static final String NULL_PASS = "****";

    private static final String KEY_ROLES = "roles";

    public static UserVo parseToken(String token, String key) {
        Claims body = Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody();
        String id = body.getId();
        String username = body.getSubject();
        String openId = String.valueOf(body.get("openId"));
        Integer type = (Integer) body.get("type");
//		List<GrantedAuthority> authorities = JwtUtils.toAuthorities(body);

        return new UserVo(Long.parseLong(id), username, JwtUtils.NULL_PASS, openId, true, type);
    }

    public static String generateToken(UserVo user, String key) {
        Claims claims = Jwts.claims();
        claims.setSubject(user.getUsername());
        claims.setId(String.valueOf(user.getId()));
        claims.put("openId", user.getOpenId());
        claims.put("type", user.getType());

//		claims.put(JwtUtils.KEY_ROLES, JwtUtils.toString(user.getAuthorities()));

        return Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS512, key).compact();
    }

    private static List<GrantedAuthority> toAuthorities(Claims body) {
        String strRoles = (String) body.get(JwtUtils.KEY_ROLES);
        String[] roles = strRoles.split(",");
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        for (String role : roles) {
            authorities.add(new SimpleGrantedAuthority(role));
        }
        return authorities;
    }

    private static String toString(Collection<GrantedAuthority> authorities) {
        StringBuilder strRoles = new StringBuilder();
        for (GrantedAuthority authority : authorities) {
            strRoles.append(authority.getAuthority() + ",");
        }
        return strRoles.substring(0, strRoles.length() - 1);
    }

}
